package com.niannian.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.niannian.MyApplication;
import com.niannian.R;
import com.niannian.bean.DownloadItemBean;
import com.niannian.util.FileUtils;
import com.niannian.util.MessageRecieveManager;
import com.niannian.util.SpocketHelper;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;

public class UpdateVersionService extends Service {
	private static UpdateVersionService service;
	private Notification notification;
	private NotificationManager notificationManager;
	public static boolean isDownloading = false;
	private int[] lock = new int[0];
	private DownloadItemBean apkInfo;
	private final int PROGRESS = 0, SUCCESS = 1, FAILED = 2;
	public static final String UPDATE_STATUS_ACTION = "UpdateVersionService.UPDATE_STATUS_ACTION";
	private NotificationReceiver notificationReceiver;

	public static UpdateVersionService getUpdateVersionServiceInstance() {
		return service;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		service = this;
		notification = new Notification();
		notification.icon = R.drawable.logo;
		notification.contentView = new RemoteViews(getPackageName(), R.layout.download_item);
		Log.i("onCreate Notification", "notification.flags" + notification.flags);
		notification.flags = (Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE);
		Intent intent = new Intent(UPDATE_STATUS_ACTION);
		PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.contentIntent = contentIntent;
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		registerMessageReceiver();
	}

	@Override
	public void onDestroy() {
		service = null;
		if (notificationReceiver != null)
			unregisterReceiver(notificationReceiver);
		super.onDestroy();
	}

	public void registerMessageReceiver() {
		notificationReceiver = new NotificationReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(MessageRecieveManager.MESSAGE_RECEIVED_PRIORITY_MAIN);
		filter.addAction(UPDATE_STATUS_ACTION);
		registerReceiver(notificationReceiver, filter);
	}

	public class NotificationReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (UPDATE_STATUS_ACTION.equals(action) && !isDownloading) {
				startDownload();
			}
		}
	}

	private void startDownload() {
		if (apkInfo != null) {
			isDownloading = true;
			notification.tickerText = "准备下载";
			notification.contentView.setTextViewText(R.id.download_title, apkInfo.title);
			notification.contentView.setTextViewText(R.id.download_progress, "准备下载");
			notification.contentView.setProgressBar(R.id.download_progressbar, 100, 0, false);
			notification.flags = (Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_SHOW_LIGHTS);
			notification.defaults = Notification.DEFAULT_LIGHTS;
			notification.ledARGB = Color.BLUE;
			notification.ledOnMS = 5000;
			notification.when = System.currentTimeMillis();
			notificationManager.notify(MyApplication.UPDATE_VERSION_NOTIFICATION_ID, notification);
			new Thread(new downloadRunable()).start();
		} else {
			isDownloading = false;
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			synchronized (lock) {
				if (!isDownloading) {
					Log.i("onStartCommand", "download now");
					apkInfo = (DownloadItemBean) intent.getSerializableExtra("download");
					startDownload();
				} else {
					Log.i("onStartCommand", "is downloading");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return Service.START_STICKY_COMPATIBILITY;
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case PROGRESS:
					notification.contentView.setProgressBar(R.id.download_progressbar, 100, msg.arg1, false);
					notification.contentView.setTextViewText(R.id.download_progress, msg.arg1 + "%");
					break;

				case SUCCESS:
					isDownloading = false;
					notification.tickerText = "下载完成";
					notification.contentView.setTextViewText(R.id.download_progress, "点击安装");
					Uri uri = Uri.fromFile(new File(apkInfo.save_path));
					Intent installIntent = new Intent(Intent.ACTION_VIEW);
					installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
					PendingIntent pendingIntent = PendingIntent.getActivity(UpdateVersionService.this, 0, installIntent, 0);
					notification.flags = (Notification.FLAG_AUTO_CANCEL | Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT
							| Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_SHOW_LIGHTS);
					notification.defaults |= Notification.DEFAULT_SOUND;
					notification.ledARGB = Color.BLUE;
					notification.ledOnMS = 5000;
					notification.contentIntent = pendingIntent;
					notification.when = System.currentTimeMillis();
					SpocketHelper.openApk(uri, UpdateVersionService.this);
					// SpocketHelper.delApk(UpdateVersionService.this);

					break;
				case FAILED:
					isDownloading = false;
					notification.tickerText = "下载失败";
					notification.when = System.currentTimeMillis();
					notification.ledARGB = Color.BLUE;
					notification.ledOnMS = 5000;
					notification.defaults |= Notification.DEFAULT_SOUND;
					notification.contentView.setTextViewText(R.id.download_progress, "点击重试");
					break;
				}
				notificationManager.notify(MyApplication.UPDATE_VERSION_NOTIFICATION_ID, notification);
				if (msg.what == SUCCESS) {
					stopSelf();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		};
	};

	private class downloadRunable implements Runnable {
		@Override
		public void run() {
			try {
				File save = new File(apkInfo.save_path);
				File temp = FileUtils.createTempFile("IS", ".tmp");
				long download_size = downloadApkFile(apkInfo.url, temp);
				if (apkInfo.total_size == download_size) {
					if (!save.getParentFile().exists()) {
						save.getParentFile().mkdirs();
					}
					if (temp.renameTo(save)) {
						// 下载成功了
						notification.contentView.setProgressBar(R.id.download_progressbar, 100, 100, false);
						handler.sendEmptyMessage(SUCCESS);
						return;
					}
				} else {
					temp.delete();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			handler.sendEmptyMessage(FAILED);
		}
	}

	private long downloadApkFile(String downloadUrl, File saveFile) throws Exception {
		int downloadCount = 0;
		int currentSize = 0;
		long totalSize = 0;
		int updateTotalSize = 0;

		HttpURLConnection httpConnection = null;
		InputStream is = null;
		FileOutputStream fos = null;

		try {
			URL url = new URL(downloadUrl);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
			if (currentSize > 0) {
				httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
			}

			httpConnection.setConnectTimeout(10000);
			httpConnection.setReadTimeout(20000);
			updateTotalSize = httpConnection.getContentLength();
			Log.i("downloadApkFile", "apk total size:" + updateTotalSize);

			if (httpConnection.getResponseCode() == 404) {
				throw new Exception("fail!");
			}
			is = httpConnection.getInputStream();
			fos = new FileOutputStream(saveFile, false);
			byte buffer[] = new byte[4096];
			int readsize = 0;
			while ((readsize = is.read(buffer)) > 0) {
				fos.write(buffer, 0, readsize);
				totalSize += readsize;
				// Log.i("downloadApkFile", "download totalSize:" + totalSize);
				if ((downloadCount == 0) || (int) (totalSize * 100 / updateTotalSize) - 1 > downloadCount) {
					downloadCount += 1;
					Log.i("downloadApkFile", "downloadCount:" + downloadCount);
					Message msg = handler.obtainMessage();
					msg.what = PROGRESS;
					msg.arg1 = downloadCount;
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpConnection != null) {
				httpConnection.disconnect();
			}
			if (is != null) {
				is.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		return totalSize;
	}

}
